package filter;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;
import util.CookieUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 执行读取Cookie的过滤器
 */
@WebFilter("/login.jsp")
public class PreLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //读取Cookie中的账号和密码
        String username = CookieUtil.read(req, "username");
        String pwd = CookieUtil.read(req, "pwd");
        //如果为空，就跳转登录页面
        if(username == null || pwd == null){
            filterChain.doFilter(req,resp);
        }else{
            //进行登录验证
            UserService userService = new UserServiceImpl();
            try {
                User user = userService.login(username, pwd);
                if(user == null){
                    //验证失败重新登录
                    filterChain.doFilter(req,resp);
                }else{
                    //登录成功保存用户信息
                    req.getSession().setAttribute("user",user);
                    //验证成功跳转查询宠物servlet
                    resp.sendRedirect("findAllPets.do");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                filterChain.doFilter(req,resp);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
